package com.thunbu.lib_common.utils;

import android.app.Activity;
import android.os.Environment;
import android.util.Log;


import com.thunbu.lib_common.utils.okhttp.OkHttpUtils;
import com.thunbu.lib_common.utils.okhttp.builder.GetBuilder;
import com.thunbu.lib_common.utils.okhttp.callback.Callback;
import com.thunbu.lib_common.utils.okhttp.callback.FileCallBack;

import java.io.File;

import okhttp3.Call;
import okhttp3.Request;

import static android.os.Environment.DIRECTORY_DOWNLOADS;

/**
 * Created by Administrator on 2016/8/31.
 */
public class EOPManager {

    private final static String TAG = EOPManager.class.getSimpleName();
    private final static String TAG_DOWN_LOAD = "downLoad";

    public static void downloadAPP(final Activity context, String appDownloadUrl, ProgressListener listener) {

        // 先取消以前可能存在的下载，再进行下载
        cancel();
        final String destFileName = appDownloadUrl.substring(appDownloadUrl.lastIndexOf("/") + 1);

        OkHttpUtils.get()
                .url(appDownloadUrl)
                .tag(TAG_DOWN_LOAD)
                .build()
                .execute(new FileCallBack(context.getExternalFilesDir(DIRECTORY_DOWNLOADS).toString(), destFileName) {

                    @Override
                    public void onBefore(Request request) {
                        listener.onBefore();
                    }

                    @Override
                    public void onAfter() {
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        Log.d(TAG, "失败:" + e.getMessage());
                        listener.onError(e.getMessage());
                    }

                    @Override
                    public void onSuccess() {
                        Log.d(TAG, "下载成功");
                        installAPK(context, context.getExternalFilesDir(DIRECTORY_DOWNLOADS) + File.separator + destFileName);
                        listener.onSuccess(context.getExternalFilesDir(DIRECTORY_DOWNLOADS) + File.separator + destFileName);
                    }

                    @Override
                    public void onResponse(File response) {

                    }

                    @Override
                    public void inProgress(float progress, long total) {
                        //Log.i(TAG, "进度:" + progress);
                        listener.progress(progress);
                    }
                });
    }

    public static void cancel() {
        // 先取消以前的下载，重开新的下载
        OkHttpUtils.getInstance().cancelTag(TAG_DOWN_LOAD);
    }

    private static void installAPK(final Activity context, String path) {
        InstallUtil.install(context, path);
    }

    public interface ProgressListener {
        void progress(float progress);

        void onSuccess(String fileName);

        void onError(String message);

        void onBefore();
    }
}
